<?php
/**
 * Created by PhpStorm.
 * User: henry
 * Date: 2017/2/22
 * Time: 下午6:10
 */

namespace common\utils;


class StringUtils
{
    /*
     * 使用正则表达式拆分字符串，默认使用中英文空格、逗号进行拆分
     * @param $str
     * @return array
     */
    public static function splitString($str, $pattern = '/[\s,　、]+/u')
    {
        $words = [];
        $arr = preg_split($pattern, trim($str));
        foreach ($arr as $i => $word) {
            if (!empty($word)) {
                array_push($words, $word);
            }
        }
        return $words;
    }

    /**
     * 转义solr查询时的特殊字符
     * @param $query
     * @return mixed
     */
    public static function escapeSolrQueryChars($query)
    {
        $luceneReservedCharacters = preg_quote('+-&|!(){}[]^"~*?:\\');
        $query = preg_replace_callback(
            '/([' . $luceneReservedCharacters . '])/',
            function ($matches) {
                return '\\' . $matches[0];
            },
            $query);
        return $query;
    }

    //第一个是原串,第二个是 部份串
    public static function startWith($str, $needle)
    {

        return strpos($str, $needle) === 0;

    }

    //第一个是原串,第二个是 部份串
    public static function endWith($haystack, $needle)
    {

        $length = strlen($needle);
        if ($length == 0) {
            return true;
        }
        return (substr($haystack, -$length) === $needle);
    }

    /**
     *  过滤HTML
     * @param $descclear
     * @return mixed
     */
    public static function filtHtml($descclear)
    {

        return strip_tags($descclear);
    }


    /**
     * 截取首标点符号
     * @param $content
     * @return string
     */
    public static function subFirstpPunctuation($content)
    {
        $punctuation = ['，', ';', '。', '!'];
        foreach ($punctuation as $item) {
            if (strpos($content, $item) === 0) {
                return mb_substr($content, 1);
            }
        }
        return $content;
    }

    /**
     * 过滤非utf-8字符
     * @param $str
     * @return string
     */
    public static function utf8_clean($str)
    {
        return iconv('UTF-8', 'UTF-8//IGNORE', $str);
    }

    /*
     * 高亮字符串
     * @param $str
     * @param $keys
     * @param $prefix
     * @param $suffix
     * @return string
     */
    public static function highlightString($str, $keys, $prefix = '<em class="_high">', $suffix = '</em>')
    {
        if (empty($str) || empty($keys))
            return $str;
        if (is_array($str)) {
            foreach ($str as &$item){
                $item = self::highlightString($item, $keys, $prefix, $suffix);
            }
            return $str;
        }
        if (is_string($keys)) {
            $keys = preg_split('//u', $keys, null, PREG_SPLIT_NO_EMPTY);
        }
        $result = $str;
        foreach ($keys as $word) {
            if (empty(trim($word))) continue;
            $word = self::escapeSolrQueryChars($word);
//            $result = preg_replace("'" . preg_quote($word) . "'", $prefix . $word . $suffix, $result);
            $result = preg_replace('#(?=[^>]*(?=<(?!/em>)|$))'.preg_quote($word).'#',$prefix . '$0' . $suffix, $result);
        }
        $result = preg_replace("'" . $suffix . $prefix . "'", "", $result);

        return mb_convert_encoding($result, 'UTF-8', 'UTF-8');
    }

    /*
     * 分割高亮字段，将高亮部分提前显示
     * @param string $str
     * @param string $mark
     * @param int $maxPos
     * @param int $maxLen
     * @return string
     */
    public static function splitHlField($str, $mark = '<em', $maxPos = 20, $maxLen = 50)
    {
        if (empty($str)) return '';

        // 得到第一次出现高亮标记的位置
        $firstFlagIndex = mb_stripos($str, $mark, 0, 'utf-8');
        if ($firstFlagIndex < $maxPos) return $str;  // 没有高亮或高亮字符串在范围之内则直接返回

        $subStrEndIndex = mb_strlen($str, 'utf-8');
        // 从高亮标记位置截取到字符末尾，如果不够 $maxLen 则再向前取相应长度的字符
        $withoutHtmlStr = self::replaceHtml(mb_substr($str, $firstFlagIndex, $subStrEndIndex - $firstFlagIndex, 'utf-8'));
        $prefixShowLen = $maxLen - mb_strlen($withoutHtmlStr, 'utf-8');
        $prefixShowLen = $prefixShowLen < 0 ? 0 : $prefixShowLen;

        $subStrStartIndex = ($firstFlagIndex >= $prefixShowLen) ? $firstFlagIndex - $prefixShowLen : 0;
        $prefix = mb_substr($str, $subStrStartIndex, $firstFlagIndex - $subStrStartIndex, 'utf-8');

        return ($subStrStartIndex == 0 ? '' : '...') . $prefix . mb_substr($str, $firstFlagIndex, $subStrEndIndex - $firstFlagIndex, 'utf-8');
    }

    /*
     * 替换 HTML 标签
     */
    public static function replaceHtml($str)
    {
        if (empty($str)) return '';
        return preg_replace('/<[^>]*>/i', '', $str);
    }
}